﻿using SerialPort_Assistant.Config;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace SerialPort_Assistant.ViewModel
{
    public class BaseViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;

        public void OnPropertyChanged([CallerMemberName] string name = "")
        {
            string typename = this.GetType().Name;
            if (this is MainViewModel)
            {
                MainViewModel? mainViewModel = this as MainViewModel;
                SetPropertyToAppConfig(mainViewModel, name);
            }
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        private void SetPropertyToAppConfig(MainViewModel model,string propertyName)
        {
            System.Reflection.PropertyInfo? modelProperty = model.GetType().GetProperty(propertyName);
            object? val = modelProperty.GetValue(model);
            AppConfig appConfig = AppConfigManager.AppConfig;
            System.Reflection.PropertyInfo? appPropertyInfo = appConfig.GetType().GetProperty(propertyName);

            if(appPropertyInfo!=null) 
            {
                appPropertyInfo.SetValue(appConfig,val);
            }
        }
    }
}
